import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';
import '../../models/user_profile_model.dart';
import '../../services/api_service.dart';
import '../../utils/logger.dart';
import '../../utils/image_utils.dart';
import 'package:base_flutter/src/network/network_exception.dart';

/// 个人资料管理页面
class UserProfileManagePage extends StatefulWidget {
  final String userId;

  const UserProfileManagePage({
    super.key,
    required this.userId,
  });

  @override
  State<UserProfileManagePage> createState() => _UserProfileManagePageState();
}

class _UserProfileManagePageState extends State<UserProfileManagePage> {
  final _apiService = ApiService();
  final _formKey = GlobalKey<FormState>();
  
  // 表单控制器
  final _nicknameController = TextEditingController();
  final _signatureController = TextEditingController();
  final _emailController = TextEditingController();
  final _phoneController = TextEditingController();
  
  // 状态变量
  UserProfileModel? _userProfile;
  List<UserTagModel> _availableTags = [];
  List<String> _selectedTags = [];
  String _selectedGender = 'other';
  DateTime? _selectedBirthDate;
  String? _avatarUrl;
  bool _isLoading = false;
  bool _isSaving = false;

  @override
  void initState() {
    super.initState();
    _loadUserProfile();
    _loadAvailableTags();
  }

  @override
  void dispose() {
    _nicknameController.dispose();
    _signatureController.dispose();
    _emailController.dispose();
    _phoneController.dispose();
    super.dispose();
  }

  /// 加载用户个人资料
  Future<void> _loadUserProfile() async {
    setState(() => _isLoading = true);
    
    try {
      final profile = await _apiService.getUserProfile(widget.userId);
      setState(() {
        _userProfile = profile;
        _nicknameController.text = profile.nickname ?? '';
        _signatureController.text = profile.signature ?? '';
        _emailController.text = profile.email ?? '';
        _phoneController.text = profile.phone ?? '';
        _selectedGender = profile.gender ?? 'other';
        _selectedBirthDate = profile.birthDate;
        _avatarUrl = profile.avatarUrl;
        _selectedTags = profile.skillTags?.map((tag) => tag.tagName).toList() ?? [];
      });
      
      Logger.d('UserProfileManagePage', '加载用户个人资料成功');
      Logger.d('UserProfileManagePage', '头像URL: $_avatarUrl');
      Logger.d('UserProfileManagePage', '昵称: ${profile.nickname}');
    } catch (e) {
      Logger.e('UserProfileManagePage', '加载用户个人资料失败: $e');
      _showErrorSnackBar('加载个人资料失败');
    } finally {
      setState(() => _isLoading = false);
    }
  }

  /// 加载可用标签
  Future<void> _loadAvailableTags() async {
    try {
      final tags = await _apiService.getAvailableTags();
      setState(() => _availableTags = tags);
      Logger.d('UserProfileManagePage', '加载可用标签成功，数量: ${tags.length}');
    } catch (e) {
      Logger.e('UserProfileManagePage', '加载可用标签失败: $e');
    }
  }

  /// 显示头像选择底部菜单
  Future<void> _showAvatarPickerBottomSheet() async {
    showModalBottomSheet(
      context: context,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      builder: (context) => SafeArea(
        child: Padding(
          padding: const EdgeInsets.all(20),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              const Text(
                '选择头像',
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                ),
              ),
              const SizedBox(height: 20),
              ListTile(
                leading: Container(
                  padding: const EdgeInsets.all(10),
                  decoration: BoxDecoration(
                    color: Colors.blue.withOpacity(0.1),
                    borderRadius: BorderRadius.circular(10),
                  ),
                  child: const Icon(Icons.camera_alt, color: Colors.blue),
                ),
                title: const Text('拍照'),
                onTap: () {
                  Navigator.pop(context);
                  _pickAvatar(ImageSource.camera);
                },
              ),
              ListTile(
                leading: Container(
                  padding: const EdgeInsets.all(10),
                  decoration: BoxDecoration(
                    color: Colors.green.withOpacity(0.1),
                    borderRadius: BorderRadius.circular(10),
                  ),
                  child: const Icon(Icons.photo_library, color: Colors.green),
                ),
                title: const Text('从相册选择'),
                onTap: () {
                  Navigator.pop(context);
                  _pickAvatar(ImageSource.gallery);
                },
              ),
              if (_avatarUrl != null)
                ListTile(
                  leading: Container(
                    padding: const EdgeInsets.all(10),
                    decoration: BoxDecoration(
                      color: Colors.red.withOpacity(0.1),
                      borderRadius: BorderRadius.circular(10),
                    ),
                    child: const Icon(Icons.delete, color: Colors.red),
                  ),
                  title: const Text('删除头像'),
                  onTap: () {
                    Navigator.pop(context);
                    setState(() => _avatarUrl = null);
                    _showSuccessSnackBar('头像已删除');
                  },
                ),
            ],
          ),
        ),
      ),
    );
  }

  /// 选择头像
  Future<void> _pickAvatar(ImageSource source) async {
    try {
      final ImagePicker picker = ImagePicker();
      final XFile? image = await picker.pickImage(
        source: source,
        maxWidth: 1024,
        maxHeight: 1024,
        imageQuality: 85,
      );
      
      if (image != null) {
        // 显示上传中提示
        _showLoadingDialog('正在上传头像...');
        
        try {
          // 上传头像到服务器
          final file = File(image.path);
          final response = await _apiService.uploadAvatar(file);
          
          // 关闭加载对话框
          if (mounted) Navigator.pop(context);
          
          // 从响应中提取头像URL
          String? uploadedUrl;
          if (response['code'] == 200 || response['code'] == 0) {
            uploadedUrl = response['data'] as String?;
          }
          
          if (uploadedUrl != null && uploadedUrl.isNotEmpty) {
            // 更新头像URL
            setState(() => _avatarUrl = uploadedUrl);
            _showSuccessSnackBar('头像上传成功');
            Logger.d('UserProfileManagePage', '头像上传成功: $uploadedUrl');
          } else {
            throw Exception('上传失败：未返回有效的URL');
          }
        } catch (uploadError) {
          // 关闭加载对话框
          if (mounted) Navigator.pop(context);
          
          Logger.e('UserProfileManagePage', '头像上传失败: $uploadError');
          _showErrorSnackBar('头像上传失败，请重试');
        }
      }
    } catch (e) {
      Logger.e('UserProfileManagePage', '选择头像失败: $e');
      _showErrorSnackBar('选择头像失败');
    }
  }

  /// 显示加载对话框
  void _showLoadingDialog(String message) {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => PopScope(
        canPop: false,
        child: Center(
          child: Card(
            child: Padding(
              padding: const EdgeInsets.all(20),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  const CircularProgressIndicator(),
                  const SizedBox(height: 16),
                  Text(message),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  /// 选择出生日期
  Future<void> _selectBirthDate() async {
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: _selectedBirthDate ?? DateTime.now().subtract(const Duration(days: 365 * 20)),
      firstDate: DateTime(1900),
      lastDate: DateTime.now(),
    );
    
    if (picked != null) {
      setState(() => _selectedBirthDate = picked);
    }
  }

  /// 保存个人资料
  Future<void> _saveProfile() async {
    if (!_formKey.currentState!.validate()) {
      return;
    }

    setState(() => _isSaving = true);

    try {
      final updateData = UpdateUserProfileDTO(
        nickname: _nicknameController.text.trim(),
        avatarUrl: _avatarUrl,
        signature: _signatureController.text.trim(),
        gender: _selectedGender,
        birthDate: _selectedBirthDate?.toIso8601String().split('T')[0],
        email: _emailController.text.trim(),
        phone: _phoneController.text.trim(),
        skillTags: _selectedTags,
      );

      await _apiService.updateUserProfile(widget.userId, updateData);
      
      _showSuccessSnackBar('保存成功');
      Navigator.pop(context, true); // 返回并传递成功标志
      
      Logger.d('UserProfileManagePage', '保存个人资料成功');
    } catch (e) {
      Logger.e('UserProfileManagePage', '保存个人资料失败: $e');
      _showErrorSnackBar('保存失败');
    } finally {
      setState(() => _isSaving = false);
    }
  }

  /// 显示错误提示
  void _showErrorSnackBar(String message) {
    if (!mounted) return;
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Row(
          children: [
            const Icon(Icons.error_outline, color: Colors.white),
            const SizedBox(width: 12),
            Expanded(child: Text(message)),
          ],
        ),
        backgroundColor: Colors.red,
        behavior: SnackBarBehavior.floating,
        duration: const Duration(seconds: 3),
      ),
    );
  }

  /// 显示成功提示
  void _showSuccessSnackBar(String message) {
    if (!mounted) return;
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Row(
          children: [
            const Icon(Icons.check_circle_outline, color: Colors.white),
            const SizedBox(width: 12),
            Expanded(child: Text(message)),
          ],
        ),
        backgroundColor: Colors.green,
        behavior: SnackBarBehavior.floating,
        duration: const Duration(seconds: 2),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[50],
      appBar: AppBar(
        title: const Text('个人资料'),
        backgroundColor: Colors.white,
        foregroundColor: Colors.black87,
        elevation: 1,
        actions: [
          TextButton(
            onPressed: _isSaving ? null : _saveProfile,
            child: Text(
              '保存',
              style: TextStyle(
                color: _isSaving ? Colors.grey : Colors.blue,
                fontWeight: FontWeight.w600,
              ),
            ),
          ),
        ],
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : SingleChildScrollView(
              padding: const EdgeInsets.all(16),
              child: Form(
                key: _formKey,
                child: Column(
                  children: [
                    _buildAvatarSection(),
                    const SizedBox(height: 24),
                    _buildBasicInfoSection(),
                    const SizedBox(height: 24),
                    _buildSkillTagsSection(),
                  ],
                ),
              ),
            ),
    );
  }

  /// 构建头像区域
  Widget _buildAvatarSection() {
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            spreadRadius: 1,
            blurRadius: 4,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        children: [
          const Text(
            '头像',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 16),
          GestureDetector(
            onTap: _showAvatarPickerBottomSheet,
            child: Stack(
              children: [
                // 使用安全的头像加载工具
                ImageUtils.safeAvatarImage(
                  _avatarUrl,
                  size: 120,
                ),
                Positioned(
                  bottom: 0,
                  right: 0,
                  child: Container(
                    padding: const EdgeInsets.all(8),
                    decoration: BoxDecoration(
                      color: Colors.blue,
                      shape: BoxShape.circle,
                      border: Border.all(color: Colors.white, width: 2),
                    ),
                    child: const Icon(
                      Icons.camera_alt,
                      color: Colors.white,
                      size: 20,
                    ),
                  ),
                ),
              ],
            ),
          ),
          const SizedBox(height: 12),
          TextButton.icon(
            onPressed: _showAvatarPickerBottomSheet,
            icon: const Icon(Icons.edit),
            label: const Text('更换头像'),
            style: TextButton.styleFrom(
              foregroundColor: Colors.blue,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建基本信息区域
  Widget _buildBasicInfoSection() {
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            spreadRadius: 1,
            blurRadius: 4,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '基本信息',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 20),
          
          // 昵称
          TextFormField(
            controller: _nicknameController,
            decoration: const InputDecoration(
              labelText: '昵称',
              hintText: '请输入昵称',
              border: OutlineInputBorder(),
              prefixIcon: Icon(Icons.person_outline),
            ),
            maxLength: 50,
            validator: (value) {
              if (value == null || value.trim().isEmpty) {
                return '昵称不能为空';
              }
              if (value.trim().length > 50) {
                return '昵称长度不能超过50个字符';
              }
              return null;
            },
          ),
          const SizedBox(height: 16),
          
          // 个性签名
          TextFormField(
            controller: _signatureController,
            decoration: const InputDecoration(
              labelText: '个性签名',
              hintText: '请输入个性签名（选填）',
              border: OutlineInputBorder(),
              prefixIcon: Icon(Icons.edit_note),
              alignLabelWithHint: true,
            ),
            maxLines: 3,
            maxLength: 500,
            validator: (value) {
              if (value != null && value.length > 500) {
                return '个性签名长度不能超过500个字符';
              }
              return null;
            },
          ),
          const SizedBox(height: 16),
          
          // 性别选择
          DropdownButtonFormField<String>(
            value: _selectedGender,
            decoration: const InputDecoration(
              labelText: '性别',
              border: OutlineInputBorder(),
              prefixIcon: Icon(Icons.wc_outlined),
            ),
            items: const [
              DropdownMenuItem(value: 'male', child: Text('男')),
              DropdownMenuItem(value: 'female', child: Text('女')),
              DropdownMenuItem(value: 'other', child: Text('其他')),
            ],
            onChanged: (value) => setState(() => _selectedGender = value!),
          ),
          const SizedBox(height: 16),
          
          // 出生日期
          InkWell(
            onTap: _selectBirthDate,
            child: InputDecorator(
              decoration: const InputDecoration(
                labelText: '出生日期',
                border: OutlineInputBorder(),
                prefixIcon: Icon(Icons.cake_outlined),
                suffixIcon: Icon(Icons.calendar_today, size: 20),
              ),
              child: Text(
                _selectedBirthDate != null
                    ? '${_selectedBirthDate!.year}-${_selectedBirthDate!.month.toString().padLeft(2, '0')}-${_selectedBirthDate!.day.toString().padLeft(2, '0')}'
                    : '请选择出生日期',
                style: TextStyle(
                  color: _selectedBirthDate != null ? Colors.black87 : Colors.grey[600],
                ),
              ),
            ),
          ),
          const SizedBox(height: 16),
          
          // 邮箱
          TextFormField(
            controller: _emailController,
            decoration: const InputDecoration(
              labelText: '邮箱',
              hintText: '请输入邮箱地址',
              border: OutlineInputBorder(),
              prefixIcon: Icon(Icons.email_outlined),
            ),
            keyboardType: TextInputType.emailAddress,
            validator: (value) {
              if (value != null && value.isNotEmpty) {
                // 邮箱正则表达式
                final emailRegex = RegExp(
                  r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$',
                );
                if (!emailRegex.hasMatch(value)) {
                  return '请输入有效的邮箱地址';
                }
              }
              return null;
            },
          ),
          const SizedBox(height: 16),
          
          // 手机号
          TextFormField(
            controller: _phoneController,
            decoration: const InputDecoration(
              labelText: '手机号',
              hintText: '请输入手机号',
              border: OutlineInputBorder(),
              prefixIcon: Icon(Icons.phone_outlined),
            ),
            keyboardType: TextInputType.phone,
            maxLength: 11,
            validator: (value) {
              if (value != null && value.isNotEmpty) {
                // 手机号正则表达式（中国大陆）
                final phoneRegex = RegExp(r'^1[3-9]\d{9}$');
                if (!phoneRegex.hasMatch(value)) {
                  return '请输入有效的手机号码';
                }
              }
              return null;
            },
          ),
        ],
      ),
    );
  }

  /// 构建技能标签区域
  Widget _buildSkillTagsSection() {
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            spreadRadius: 1,
            blurRadius: 4,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '技能标签',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 12),
          const Text(
            '选择您的专业技能标签',
            style: TextStyle(
              fontSize: 14,
              color: Colors.grey,
            ),
          ),
          const SizedBox(height: 16),
          Wrap(
            spacing: 8,
            runSpacing: 8,
            children: _availableTags.map((tag) {
              final isSelected = _selectedTags.contains(tag.tagName);
              return GestureDetector(
                onTap: () {
                  setState(() {
                    if (isSelected) {
                      _selectedTags.remove(tag.tagName);
                    } else {
                      _selectedTags.add(tag.tagName);
                    }
                  });
                },
                child: Container(
                  padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                  decoration: BoxDecoration(
                    color: isSelected ? Colors.blue.withOpacity(0.2) : Colors.grey[100],
                    borderRadius: BorderRadius.circular(20),
                    border: Border.all(
                      color: isSelected ? Colors.blue : Colors.grey[300]!,
                      width: isSelected ? 2 : 1,
                    ),
                  ),
                  child: Text(
                    tag.tagName,
                    style: TextStyle(
                      color: isSelected ? Colors.blue : Colors.grey[700],
                      fontSize: 14,
                      fontWeight: isSelected ? FontWeight.w600 : FontWeight.w500,
                    ),
                  ),
                ),
              );
            }).toList(),
          ),
        ],
      ),
    );
  }
}

